/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

import React, { useState } from 'react';
import { connect, useHistory } from 'dva';
import { Button, Form, Input, message, Table } from 'antd';
import { useAntdTable } from 'ahooks';
import { brandsMap_name } from '@/utils/utils';
import QuoteModal from './quoteModal';

const FormItem = Form.Item;
const statusList = {
  1: {
    text: '待确认',
    cname: {},
  },
  2: {
    text: '使用中',
    cname: {},
  },
  3: {
    text: '已拒绝',
    cname: { color: 'red' },
  },
  4: {
    text: '已拒绝',
    cname: { color: 'red' },
  },
};

const Setting = props => {
  const { dispatch, form } = props;

  const { getFieldDecorator } = form;

  const [currentModalData, setCurrentModalData] = useState(null);
  const [modalDataId, setModalDataId] = useState('');
  const [selectedRowKeys, setSelectedRowKeys] = useState([]);

  const history = useHistory();

  const getTableData = (res, formData) =>
    dispatch({
      type: 'order_finance/getFinanceList',
      payload: {
        ...res,
        ...formData,
        page: res.current,
      },
    }).then(ress => ({
      total: ress.data.total,
      list: ress.data.list,
    }));
  const { tableProps, search, loading } = useAntdTable(getTableData, {
    defaultPageSize: 10,
    form,
  });
  const { submit } = search;

  const columns = [
    {
      title: '驿站名称',
      dataIndex: 'company_name',
      key: 'company_name',
      align: 'center',
    },
    {
      title: '联系电话',
      dataIndex: 'phone',
      key: 'phone',
      align: 'center',
    },
    {
      title: '设置的报价单',
      dataIndex: 'qoute_name',
      key: 'qoute_name',
      align: 'center',
      render: (_, { quotation }) => {
        if (quotation.length) {
          return (
            <>
              {quotation.map(item => (
                <div key={item.id}>{item.name}</div>
              ))}
            </>
          );
        }
        return <div>暂未设置报价单</div>;
      },
    },
    {
      title: '快递品牌',
      dataIndex: 'brand',
      key: 'brand',
      align: 'center',
      render: (_, { quotation }) => {
        if (quotation.length) {
          return (
            <>
              {quotation.map(item => (
                <div key={item.id}>{brandsMap_name(item.brand)}</div>
              ))}
            </>
          );
        }
        return <div>--</div>;
      },
    },
    {
      title: '驿站状态',
      dataIndex: 'status',
      key: 'status',
      align: 'center',
      render: (_, { quotation }) => {
        if (quotation.length) {
          return (
            <>
              {quotation.map(item => (
                <div style={{ ...statusList[item.leaguer_status].cname }} key={item.id}>
                  {statusList[item.leaguer_status].text}
                </div>
              ))}
            </>
          );
        }
        return <div>--</div>;
      },
    },
    {
      title: '操作报价单',
      dataIndex: 'operanor',
      key: 'operanor',
      align: 'center',
      render: (_, record) => <a onClick={setModalData.bind(null, record)}>设置</a>,
    },
  ];

  const setModalData = record => {
    setCurrentModalData(record.quotation || []);
    setModalDataId(record.cm_id);
  };

  const onModalClose = () => {
    setCurrentModalData(null);
    setModalDataId('');
  };

  const modalSubmit = params => {
    dispatch({
      type: 'order_finance/setInnQuotation',
      payload: {
        ...params,
        cm_id: modalDataId || selectedRowKeys.join(','),
      },
    }).then(() => {
      message.success('设置成功', 1);
      onModalClose();
      submit();
      setSelectedRowKeys([]);
    });
  };

  const addNewQuote = () => {
    history.push('/order/finance/finance_add');
  };

  const onSelectRow = keys => {
    setSelectedRowKeys(keys);
  };

  const onBatchSetting = () => {
    setCurrentModalData([]);
  };

  return (
    <div>
      <div style={{ marginBottom: 16 }}>
        <Form layout="inline">
          <FormItem>
            {getFieldDecorator('keyword', {
              initialValue: '',
            })(<Input placeholder="可根据驿站手机号或名称搜索" style={{ width: 300 }} />)}
          </FormItem>
          <FormItem>
            <Button type="primary" icon="search" onClick={submit}>
              搜索
            </Button>
          </FormItem>
          <FormItem>
            <Button type="primary" onClick={addNewQuote}>
              添加报价单
            </Button>
          </FormItem>
          <FormItem>
            <Button type="primary" disabled={selectedRowKeys.length == 0} onClick={onBatchSetting}>
              批量设置报价单
            </Button>
          </FormItem>
        </Form>
      </div>
      <Table
        loading={loading}
        columns={columns}
        rowKey="cm_id"
        rowSelection={{
          selectedRowKeys,
          onChange: onSelectRow,
        }}
        {...tableProps}
      />
      <QuoteModal data={currentModalData} onClose={onModalClose} modalSubmit={modalSubmit} />
    </div>
  );
};

export default connect(result => {
  const { loading, order_finance } = result;
  return {
    loading,
    order_finance,
  };
})(Form.create()(Setting));
